'use strict';
import React from 'react';
import {AutoComplete, Button, Form, Icon, Input, InputNumber, Modal, notification, Select, Upload} from 'antd';

import {FormField, FormLayout, ModalFooter} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';

import notify from "../../../components/NotificationExtra";

moment.locale('zh-cn');

@Form.create()
@connect(({
            tenant,
            global,
            vendor,
            dic, finance, dict, customer
          }) => ({...tenant, ...dic, ...vendor, ...global, ...finance, ...dict, ...customer}))
export default class ModalCreateOrEditInvoiceRecord extends FormBase {
  constructor(props) {
    super(props);
    const {record} = this.props;
    this.state = {...record};

  }

  componentDidMount() {
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'vendor/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });
  }


  renderFoot = () => {
    const {foot, value, callback, modalRef, record, form} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }

              // _.map(this.state, (item, key) => {
              //   values[key] = item;
              // });
              const {name, code, fileList} = this.state;
              values.recordId = record ? record.recordId : undefined;
              values.name = name;
              values.code = code;
              values.fileList = fileList;
              callback(values);
              modalRef.close();
            });

          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  picHandlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
      console.log(file.preview);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true
    });
  };
  picHandleChange = ({fileList}) => {
    _.map(fileList, async file => {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
        //file.thumbUrl = file.response ? file.response.data : fileList.file.thumbUrl;
      }
    });
    const temp = this.state;
    temp.fileList = fileList;
    this.setState({...temp});
  };

  render() {
    const {form, vendors = [], divisionDict = [], customers = [], entityType = '客户'} = this.props;
    let {
      fileList, name, amount, invoiceNumber, division, taxRate,
      previewVisible,
      previewImage
    } = this.state;
    const divisionName = entityType === '客户' ? '销售公司' : '采购公司';
    return (
      <Form>
        {<FormLayout form={form} cols={1}>
          <FormField
            label={entityType}
            name={'name'}
            initialValue={name}
            required={true}
          >
            <AutoComplete style={{width: '100%'}}
                          dataSource={this.getCustomerOpt(entityType === '客户' ? customers : vendors)}
                          allowClear
                          onChange={value => {
                            if (!value) {
                              this.state['name'] = '';
                              this.state['code'] = '';
                            }
                          }}
                          onSelect={(value, option) => {
                            const {key, props} = option;
                            this.state['code'] = key;
                            this.state['name'] = value;
                          }}
              // onSearch={searchText => {
              //
              //   const {customers = []} = this.props;
              //   if (!searchText || searchText === '') {
              //     this.state.customers = customers;
              //     const _temp = this.state;
              //     this.setState(_temp);
              //     return;
              //   }
              //
              //   const temp = [];
              //   _.map(this.props.customers, item => {
              //     const {name} = item;
              //     if (name.includes(searchText)) {
              //       temp.push(item);
              //     }
              //   });
              //   const _temp = this.state;
              //   _temp.customers = temp;
              //   this.setState(_temp);
              // }}
            >
            </AutoComplete>
          </FormField>
          <FormField
            label={divisionName}
            name={'division'}
            initialValue={division}
            required={true}
          >
            <Select allowClear>{this.getDivision(divisionDict)}</Select>
          </FormField>
          <FormField
            label={'发票号'}
            name={'invoiceNumber'}
            initialValue={invoiceNumber}
            required={true}
          >
            <Input style={{width: '100%'}}
            ></Input>
          </FormField>
          <FormField
            label={'开票金额'}
            name={'amount'}
            initialValue={amount}
            required={true}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'税率'}
            name={'taxRate'}
            initialValue={taxRate}
            required={true}
          >
            <Select allowClear style={{width: '100%'}}>
              {this.getSelectOption(this.taxRateOption1)}
            </Select>
          </FormField>
        </FormLayout>
        }
        {
          <div style={{marginLeft: '64px'}}>
            <Upload
              action={'http://127.0.0.1:18008/api/global/upload?type=inboundLot'} // 没有用，直接存图片流文件
              listType="picture-card"
              fileList={fileList}
              accept={".png,.jpg"}
              onPreview={this.picHandlePreview}
              onChange={this.picHandleChange}
              onDownload={file => {
                console.log('ondownlad', file);
              }}
              beforeUpload={(file, fileList) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  notify({type: 'error', message: '文件过大！'});
                  return isLt2M;
                }
                return false;
              }}
            >
              {<div>
                <Icon type="plus"/>
                <div className="ant-upload-text">上传图片</div>
              </div>}
            </Upload>
            <Modal visible={previewVisible} footer={null} onCancel={() => {
              this.setState({previewVisible: false});
            }}>
              <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
          </div>
        }
        {this.renderFoot()}
      </Form>
    );
  }
}
